﻿using Infrastructure.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DomenModel;
using OMS.Models;
using Model.Service;
using Infrastructure.Repositories;
using OMS.Infrastructure;

namespace OMS.Controllers
{
   
    public class AdministrationController : Controller
    {

        private IAdministratorService _service;
        private IAuthorizationProvider prov;
        public AdministrationController(IAdministratorService _service, IAuthorizationProvider prov)
        {
            this._service = _service;
            this.prov = prov;
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Index()
        {
            
             ViewBag.currentPage = 1;
             ViewBag.itemOnPage = 10;
             ViewBag.CheckBox = false;
             ViewBag.Users = _service.GetPaginationListOfUsers(1, ViewBag.itemOnPage, null);
             ViewBag.UsersCount = _service.GetCountOfUsers();
             
             if (ViewBag.UsersCount % ViewBag.itemOnPage != 0) ViewBag.lastPage = ViewBag.UsersCount / ViewBag.itemOnPage + 1;
             else ViewBag.lastPage = ViewBag.UsersCount / ViewBag.itemOnPage;

             ViewBag.numberOfUsersOnline = prov.GetNumberOfUsersOnline();
             ViewBag.dictionaryOfUsersOnline = prov.GetDictionaryOfUsersOnline();
             return View();
        }


        public ActionResult CreateUser()
        {
            //throw new Exception();
            return View();
        }

        [HttpPost]
        public ActionResult CreateUser(CreateUser model)
        {
            bool statusOfSafe;
            if (ModelState.IsValid)
            {
                User user = new User
                {
                    LoginName = model.LoginName,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    Password = model.Password,
                    Email = model.Email,
                    Region = model.Region,
                    RoleId = model.Role,
                    Balance = 0,
                    StatusId = 1,
                    IsActive = true,
                };

                statusOfSafe = _service.CreateUser(user);
                if (statusOfSafe == true) ModelState.AddModelError("","User are create");
            }
            else
            {
                ModelState.AddModelError("", "User not valid");
            }
                    

            return View(model);
        }

        [HttpGet]
        public ActionResult Edit(string userLogin)
        {
            var user = _service.GetUser(userLogin); 
            EditUser model = new EditUser();

            model.LoginName = user.LoginName;
            model.FirstName = user.FirstName;
            model.LastName = user.LastName;
            model.Region = user.Region;
            model.Email = user.Email;
            model.Password = user.Password;
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(EditUser model)
        {
            if (ModelState.IsValid)
            {
                var user = _service.GetUser(model.LoginName); 
                    user.FirstName = model.FirstName;
                    user.LastName = model.LastName;
                    user.Password = model.Password;
                    user.Email = model.Email;
                    user.Region = model.Region;
                    user.RoleId = model.Role;
                    
                bool check = _service.EditUser(user);
                return RedirectToAction("Index");
            }
            else
            {
                ModelState.AddModelError("", "User not valid");
            }
            return View(model);
        }


        [HttpGet]
        public ActionResult Dublicate(string userLogin)
        {
            var user = _service.GetUser(userLogin);
            CreateUser model = new CreateUser();

            model.LoginName = user.LoginName;
            model.FirstName = user.FirstName;
            model.LastName = user.LastName;
            model.Region = user.Region;
            model.Email = user.Email;
            model.Password = user.Password;

            return View(model);
        }

        [HttpPost]
        public ActionResult Dublicate(CreateUser model)
        {
            bool statusOfSafe;
            if (ModelState.IsValid)
            {
                User user = new User
                {
                    LoginName = model.LoginName,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    Password = model.Password,
                    Email = model.Email,
                    Region = model.Region,
                    RoleId = model.Role,
                    Balance = 0,
                    StatusId = 1,
                    IsActive = true,
                };

                statusOfSafe = _service.CreateUser(user);
                if (statusOfSafe == true) ModelState.AddModelError("", "User are create");
            }
            else
            {
                ModelState.AddModelError("", "User not valid");
            }


            return View(model);
        }



        public ActionResult Delete(string userLogin, string confidence)
        {
            
            ViewBag.user = userLogin;
        
            if (confidence == "yes")
            {
            bool statusesOfDelete = _service.DeactivateUser(userLogin);
            return RedirectToAction("Index");
            }
            return View();
        }

        [HttpPost]
        public ActionResult Delete()
        {
            bool statusesOfDelete = _service.DeactivateUser(ViewBag.user);
            return RedirectToAction("Index");
        }

        [HttpGet]
        public JsonResult CheckUserName(string LoginName)
        {
             
             var user = prov.GetUser(LoginName);

            if (user == null)
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }

            return Json(false, JsonRequestBehavior.AllowGet); 
           
        }

        [HttpGet]
        public JsonResult CheckEmail(string Email)
        {
            var user = prov.GetUserNameByEmail(Email);

            if (user == null)
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }

            return Json(false, JsonRequestBehavior.AllowGet);

        }

        public ActionResult UserTable(int? page, int? itemOnPage, string orderUsersBy, string searchString, string listSelectField, string listSelectCondition, bool statusCheckBox)
        {
            ViewBag.NameSortParm = String.IsNullOrEmpty(orderUsersBy) ? "UserName desc" : "";
            ViewBag.SortByFirstName = orderUsersBy == "FirstName" ? "FirstName desc" : "FirstName";
            ViewBag.SortByLastName = orderUsersBy == "LastName" ? "LastName desc" : "LastName";
            ViewBag.SortByRole = orderUsersBy == "Role" ? "Role desc" : "Role";
            ViewBag.SortByEmail = orderUsersBy == "Email" ? "Email desc" : "Email";
            ViewBag.SortByRegion = orderUsersBy == "Region" ? "Region desc" : "Region";

            ViewBag.CheckBox = statusCheckBox;

            int currentPage = page ?? 1;
            ViewBag.itemOnPage = itemOnPage ?? 10;
            if (statusCheckBox == true)
            {
                if (String.IsNullOrWhiteSpace(searchString))
                {
                    ViewBag.Users = prov.GetListOfUsersOnline(_service.GetPaginationListOfUsers(currentPage, ViewBag.itemOnPage, orderUsersBy));
                    ViewBag.UsersCount = prov.GetNumberOfUsersOnline();
                }
                else
                {
                    ViewBag.Users = prov.GetListOfUsersOnline(_service.GetPaginationWithFilter(currentPage, ViewBag.itemOnPage, orderUsersBy, searchString, listSelectField, listSelectCondition));
                    ViewBag.UsersCount = prov.GetNumberOfUsersOnline();
                }
            }
            else
            {
                if (String.IsNullOrWhiteSpace(searchString))
                {
                    ViewBag.Users = _service.GetPaginationListOfUsers(currentPage, ViewBag.itemOnPage, orderUsersBy);
                    ViewBag.UsersCount = _service.GetCountOfUsers();
                }
                else
                {
                    ViewBag.Users = _service.GetPaginationWithFilter(currentPage, ViewBag.itemOnPage, orderUsersBy, searchString, listSelectField, listSelectCondition);
                    ViewBag.UsersCount = _service.GetCountOfUsers(searchString, listSelectField, listSelectCondition);
                }
            }

            if (ViewBag.UsersCount % ViewBag.itemOnPage != 0) ViewBag.lastPage = ViewBag.UsersCount / ViewBag.itemOnPage + 1;
            else ViewBag.lastPage = ViewBag.UsersCount / ViewBag.itemOnPage;

            ViewBag.currentPage = currentPage;
            ViewBag.currentSortUserBy = orderUsersBy;
            ViewBag.searchString = searchString;
            ViewBag.listSelectField = listSelectField;
            ViewBag.listSelectCondition = listSelectCondition;

            prov.UpdateUserLastActivityDate(User.Identity.Name);
            ViewBag.numberOfUsersOnline = prov.GetNumberOfUsersOnline();
            ViewBag.dictionaryOfUsersOnline = prov.GetDictionaryOfUsersOnline();

            return PartialView();
        }
    }
}
